const { db } = require('../config/database');

// 创建游戏房间
const createRoom = async (req, res) => {
  try {
    const { name, description, moduleId } = req.body;
    const kpId = req.user.id;

    // 检查模组是否存在
    const module = await db.oneOrNone(
      'SELECT id FROM modules WHERE id = $1 AND (author_id = $2 OR is_public = true)',
      [moduleId, kpId]
    );

    if (!module) {
      return res.status(404).json({ message: '模组不存在或无权限访问' });
    }

    // 创建房间
    const room = await db.one(
      `INSERT INTO rooms (name, description, module_id, kp_id, players, game_state, map_data) 
       VALUES ($1, $2, $3, $4, $5, $6, $7) 
       RETURNING id, name, description, module_id, kp_id, players, game_state, map_data, created_at`,
      [
        name,
        description,
        moduleId,
        kpId,
        JSON.stringify([]),
        JSON.stringify({}),
        JSON.stringify({})
      ]
    );

    res.status(201).json({
      message: '房间创建成功',
      room: {
        ...room,
        players: JSON.parse(room.players),
        gameState: JSON.parse(room.game_state),
        mapData: JSON.parse(room.map_data)
      }
    });
  } catch (error) {
    console.error('创建房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 加入游戏房间
const joinRoom = async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.id;

    // 检查房间是否存在且活跃
    const room = await db.oneOrNone(
      'SELECT id, players, kp_id FROM rooms WHERE id = $1 AND is_active = true',
      [roomId]
    );

    if (!room) {
      return res.status(404).json({ message: '房间不存在或已关闭' });
    }

    // 检查用户是否已在房间中
    const players = JSON.parse(room.players);
    if (players.includes(userId)) {
      return res.status(400).json({ message: '您已在此房间中' });
    }

    // 检查房间是否已满（假设最大8人）
    if (players.length >= 8) {
      return res.status(400).json({ message: '房间已满' });
    }

    // 添加玩家到房间
    players.push(userId);
    await db.none(
      'UPDATE rooms SET players = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',
      [JSON.stringify(players), roomId]
    );

    res.json({
      message: '成功加入房间',
      roomId: parseInt(roomId)
    });
  } catch (error) {
    console.error('加入房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 离开游戏房间
const leaveRoom = async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.id;

    // 检查房间是否存在
    const room = await db.oneOrNone(
      'SELECT id, players, kp_id FROM rooms WHERE id = $1',
      [roomId]
    );

    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }

    // 检查用户是否在房间中
    const players = JSON.parse(room.players);
    const playerIndex = players.indexOf(userId);

    if (playerIndex === -1) {
      return res.status(400).json({ message: '您不在此房间中' });
    }

    // 移除玩家
    players.splice(playerIndex, 1);
    await db.none(
      'UPDATE rooms SET players = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',
      [JSON.stringify(players), roomId]
    );

    res.json({
      message: '成功离开房间',
      roomId: parseInt(roomId)
    });
  } catch (error) {
    console.error('离开房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取房间列表
const getRooms = async (req, res) => {
  try {
    const { page = 1, limit = 10, status = 'active' } = req.query;
    const offset = (page - 1) * limit;

    let whereClause = '';
    if (status === 'active') {
      whereClause = 'WHERE r.is_active = true';
    } else if (status === 'my') {
      whereClause = 'WHERE r.kp_id = $1 OR $1 = ANY(SELECT jsonb_array_elements_text(r.players))';
    }

    const rooms = await db.any(
      `SELECT r.id, r.name, r.description, r.is_active, r.created_at,
              u.username as kp_name, m.name as module_name,
              jsonb_array_length(r.players) as player_count
       FROM rooms r
       JOIN users u ON r.kp_id = u.id
       JOIN modules m ON r.module_id = m.id
       ${whereClause}
       ORDER BY r.created_at DESC
       LIMIT $${status === 'my' ? 2 : 1} OFFSET $${status === 'my' ? 3 : 2}`,
      status === 'my' ? [req.user.id, limit, offset] : [limit, offset]
    );

    res.json({
      rooms,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: rooms.length
      }
    });
  } catch (error) {
    console.error('获取房间列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取房间详情
const getRoom = async (req, res) => {
  try {
    const { roomId } = req.params;

    const room = await db.oneOrNone(
      `SELECT r.*, u.username as kp_name, m.name as module_name, m.data as module_data
       FROM rooms r
       JOIN users u ON r.kp_id = u.id
       JOIN modules m ON r.module_id = m.id
       WHERE r.id = $1`,
      [roomId]
    );

    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }

    // 获取玩家信息
    const players = await db.any(
      `SELECT id, username, avatar FROM users WHERE id = ANY($1)`,
      [JSON.parse(room.players)]
    );

    res.json({
      ...room,
      players: players,
      gameState: JSON.parse(room.game_state),
      mapData: JSON.parse(room.map_data)
    });
  } catch (error) {
    console.error('获取房间详情错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  createRoom,
  joinRoom,
  leaveRoom,
  getRooms,
  getRoom
};
